package net.ycxinxing.mcpebox.ui;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ArrayAdapter;
import com.mobeta.android.dslv.DragSortListView;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import net.ycxinxing.mcpebox.CallbackBundle;
import net.ycxinxing.mcpebox.Pro.R;
import net.ycxinxing.mcpebox.ZIPUtils;
import net.ycxinxing.mcpebox.ZipCompressor;
import net.ycxinxing.mcpebox.baseActivity;
import net.ycxinxing.mcpebox.utils.OpenFileDlg;
import net.ycxinxing.mcpebox.utils.Utils;
import org.json.JSONArray;
import org.json.JSONException;

public class TextureManager extends baseActivity
{
	private DragSortListView listview;
	private ArrayAdapter<String> adapter;

	private DragSortListView.DropListener onDrop =
	new DragSortListView.DropListener() {
		@Override
		public void drop(int from, int to)
		{
			if (from != to)
			{
				String item = adapter.getItem(from);
				adapter.remove(item);
				adapter.insert(item, to);
			}
		}
	};

    private DragSortListView.RemoveListener onRemove = 
	new DragSortListView.RemoveListener() {
		@Override
		public void remove(int which)
		{
			new File("/sdcard/ycxinxing/mcpebox/texture/" + adapter.getItem(which)).delete();
			adapter.remove(adapter.getItem(which));
		}
	};


	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO: Implement this method
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_texturemanager);
		listview = (DragSortListView)findViewById(R.id.texturelist);
		listview.setDropListener(onDrop);
		listview.setRemoveListener(onRemove);
		ArrayList<String> list = new ArrayList<String>();
		try
		{
			JSONArray arr=new JSONArray(getSharedPreferences("data", MODE_PRIVATE).getString("texturepack", new JSONArray().toString()));
			int i=0;
			while (i < arr.length())
			{
				list.add(arr.get(i).toString());
				i++;
			}
		}
		catch (JSONException e)
		{
			throw new RuntimeException(e);
		}
        adapter = new ArrayAdapter<String>(this, R.layout.list_item_textrue, R.id.text, list);
		listview.setAdapter(adapter);

	}

	@Override
	public void onBackPressed()
	{
		// TODO: Implement this method
		super.onBackPressed();
		JSONArray arr=new JSONArray();

		int i=0;
		while (i < adapter.getCount())
		{
			//toast(adapter.getItem(i));
			arr.put(adapter.getItem(i));
			i++;
		}
		SharedPreferences.Editor editor=getSharedPreferences("data", MODE_PRIVATE).edit();
		editor.putString("texturepack", arr.toString());
		editor.commit();
	}

	public void addnew(View v)
	{
		showDialog(1234);
		//adapter.add("测试用"+new Random().nextInt());
	}
	@Override
	protected Dialog onCreateDialog(int id, Bundle args)
	{
		if (id == 1234)
		{
			Map<String, Integer> images = new HashMap<String, Integer>();
			// 下面几句设置各文件类型的图标， 需要你先把图标添加到资源文件夹
			images.put(OpenFileDlg.sRoot, R.drawable.fi_dir);	// 根目录图标
			images.put(OpenFileDlg.sParent, R.drawable.fi_dir);	//返回上一层的图标
			images.put(OpenFileDlg.sFolder, R.drawable.fi_dir);	//文件夹图标
			images.put("mctoolstextruepack", R.drawable.fi_file);	//文件图标
			images.put(OpenFileDlg.sEmpty, R.drawable.fi_file);
			Dialog dialog = OpenFileDlg.createDialog(1234, this, "打开文件", new CallbackBundle() {
					@Override
					public void callback(final Bundle bundle)
					{
						final ProgressDialog pd=new ProgressDialog(TextureManager.this);
						pd.setMessage("正在处理...");
						pd.setCancelable(false);
						pd.show();
						if (bundle.getString("path").endsWith(".mctoolstexturepack"))
						{
							new Thread(){
								public void run()
								{
									try
									{
										new File("/sdcard/ycxinxing/mcpebox/texture/").mkdirs();
										Utils.copyFile(new File(bundle.getString("path")), new File("/sdcard/ycxinxing/mcpebox/texture/" + new File(bundle.getString("path")).getName()));
										runOnUiThread(new Runnable(){

												@Override
												public void run()
												{

													adapter.add(new File(bundle.getString("path")).getName());
													pd.dismiss();
													// TODO: Implement this method
												}
											});

									}
									catch (Exception e)
									{
										throw new RuntimeException(e);
									}
								}
							}.start();
							}else{
								new AlertDialog.Builder(TextureManager.this).setMessage("您选择的材质为zip格式(传统mc材质包)，但是您的tools for minecraftpe已取消了对该种材质的支持。如需使用，请转换至mctoolstexturepack材质格式(这可能需要几分钟时间)").setNegativeButton("放弃", null).setPositiveButton("转换", new DialogInterface.OnClickListener(){

										@Override
										public void onClick(DialogInterface p1, int p2)
										{
											pd.setMessage("正在转换...");
											new Thread(){
												public void run()
												{
													try{
														String tmppath="/sdcard/ycxinxing/tmp/";
														new File(tmppath).mkdirs();
														new File(tmppath+"AndroidManifest.xml").createNewFile();
														new File(tmppath+"assets/resource_packs/vanilla/").mkdirs();
														ZIPUtils.unZipFolder(bundle.getString("path"),tmppath+"/assets/resource_packs/vanilla/");
														new File(tmppath+"assets/resource_packs/vanilla/pack_manifest.json").delete();
														new File(tmppath+"assets/resource_packs/vanilla/manifest.json").delete();
														ZipCompressor zip=new ZipCompressor("/sdcard/ycxinxing/mcpebox/texture/"+new File(bundle.getString("path")).getName()+".mctoolstexturepack");
														zip.compress(tmppath+"assets/",tmppath+"AndroidManifest.xml");
														Utils.deleteFile(new File(tmppath));
														runOnUiThread(new Runnable(){

																@Override
																public void run()
																{
																	adapter.add(new File(bundle.getString("path")).getName()+".mctoolstexturepack");
																	pd.dismiss();
																	// TODO: Implement this method
																}
															});
													}catch(Exception e)
													{
														throw new RuntimeException(e);
													}
												}
											}.start();
											
											
											// TODO: Implement this method
										}
									}).show();
							}
						
						// TODO: Implement this method
					}
				}, ".mctoolstexturepack;.zip;", images);
			return dialog;
		}
		return super.onCreateDialog(id, args);
	}
}
